package com.hospital.register.sms.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.hospital.register.common.constants.redis.UserRedisConstants;
import com.hospital.register.sms.constants.SmsConstants;
import com.hospital.register.sms.service.SmsService;
import com.hospital.register.sms.utils.RandomUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class SmsServiceImpl implements SmsService {

    /**
     * 访问 Redis
     */
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 日志工具
     */
    private final Logger logger = LoggerFactory.getLogger(SmsServiceImpl.class);

    @Override
    public boolean sendVerificationCode(String phone) {
        String randomCode = RandomUtil.getSixBitRandom();
        redisTemplate.opsForValue().set(UserRedisConstants.LOGIN_VERIFICATION_CODE + phone, randomCode, 10,
                TimeUnit.MINUTES);
        Map<String, Object> variables = new HashMap(1);
        variables.put("code", randomCode);

        boolean isSuccessful = this.sendShortMessage(SmsConstants.getVerificationCodeTemplate(), phone, variables);

        if (isSuccessful) {
            this.logger.info("成功发送短信验证码" + randomCode + "到" + phone);
        } else {
            this.logger.info("无法发送短信验证码" + randomCode + "到" + phone);
        }
        return isSuccessful;
    }

    /**
     * 调用阿里云接口发送验证码
     *
     * @param phone        接收验证码的手机号
     * @param templateCode 短信模板的编号
     * @param variables    短信模板的参数列表
     * @return 是否发送成功
     */
    @Override
    public boolean sendShortMessage(String templateCode, String phone, Object variables) {
        this.logger.info("发送短信验证码" + templateCode + "到" + phone + "，参数：" + variables);

        // 整合阿里云短信服务
        // 设置相关参数
        DefaultProfile profile = DefaultProfile.getProfile(SmsConstants.getRegionId(), SmsConstants.getAccessKeyId(),
                SmsConstants.getSecret());
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        // request.setProtocol(ProtocolType.HTTPS);
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");

        // 手机号
        request.putQueryParameter("PhoneNumbers", phone);
        // 签名名称
        request.putQueryParameter("SignName", "尚医通预约挂号云平台");
        // 这个模板只能发给我自己
        // 模板code
        request.putQueryParameter("TemplateCode", templateCode);
        // 验证码 使用json格式 {"code":"123456"}
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(variables));

        // 调用方法进行短信发送
        try {
            CommonResponse response = client.getCommonResponse(request);
            this.logger.info(response.getData());
            return response.getHttpResponse().isSuccess();
        } catch (ServerException e) {
            this.logger.error(e.toString());
        } catch (ClientException e) {
            this.logger.error(e.toString());
        }
        return false;
    }

}
